package com.my.netty.promote.server.handler;

import com.my.netty.promote.message.LoginRequestMessage;
import com.my.netty.promote.message.LoginResponseMessage;
import com.my.netty.promote.server.service.UserServiceFactory;
import com.my.netty.promote.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage message) throws Exception {
        log.info("用户登录请求：{}", message);
        boolean login = UserServiceFactory.getUserService().login(message.getUsername(), message.getPassword());
        LoginResponseMessage responseMessage;
        if (login) {
            //绑定channel和用户名
            SessionFactory.getSession().bind(ctx.channel(), message.getUsername());
            responseMessage = new LoginResponseMessage(true, "登录成功");
            log.info("{}登录成功", message.getUsername());
        } else {
            responseMessage = new LoginResponseMessage(false, "用户名或密码错误");
            log.info("{}登录失败", message.getUsername());
        }
        ctx.writeAndFlush(responseMessage);
    }
}
